﻿# -*- coding:utf-8 -*-
import pymongo
import json
from com.zzh.utils.table2Json_v2 import MyJsonEncoder
from bson import ObjectId


class ExportFromMongo(object):
    def __init__(self):
        self.server = pymongo.MongoClient(host='121.40.183.170', port=27017)
        self.db = self.server['zzh']
        self.collection = self.db['from_scrapy']

    def query(self, **kw):
        """
        从MongoDB查询数据，根据check_status=false来筛选出未插入到MySQL的数据
        :return:
        """
        pageIndex = kw['pageIndex']
        pageSize = kw['pageSize']
        d = []
        for data in self.collection.find({"check_status": "false"}).skip((pageIndex - 1) * pageSize).limit(pageSize):
            t = {}

            t['id'] = data['_id'] if '_id' in data.keys() else ""
            t['item_url'] = data['item_url'] if 'item_url' in data.keys() else ""
            t['item_deadline'] = data['item_deadline'] if 'item_deadline' in data.keys() else None
            t['item_title'] = data['item_title'] if 'item_title' in data.keys() else ""

            t['item_handlername'] = data['item_handlername'] if 'item_handlername' in data.keys() else ""
            t['item_pricerange'] = data['item_pricerange'] if 'item_pricerange' in data.keys() else ""

            t['item_publishdate'] = data['item_publishdate'] if 'item_publishdate' in data.keys() else None

            t['dept_id'] = data['dept_id'] if 'dept_id' in data.keys() else 0

            t['item_handlerphone'] = data['item_handlerphone'] if 'item_handlerphone' in data.keys() else ""

            t['item_content'] = data['item_content'] if 'item_content' in data.keys() else ""
            t['item_address'] = data['item_address'] if 'item_address' in data.keys() else ""
            t['dept_name'] = data['dept_name'] if 'dept_name' in data.keys() else ""
            d.append(t)
        jsonData = json.dumps(d, cls=MyJsonEncoder, ensure_ascii=False)
        total = self.collection.count({"check_status": "false"})
        return jsonData, total

    def update(self, objIds):
        """
        已经插入到MySQL的数据，根据_id在MongoDB中将check_status更新为true
        :param objId: mongoDB中唯一主键 _id
        :return:
        """
        for id0 in objIds:
            result = self.collection.update_one({"_id": ObjectId(id0)}, {"$set": {"check_status": "true"}})
        return result
